//
//  GetAddressBook.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/11.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "GetAddressBook.h"
#import <AddressBook/AddressBook.h>
#import "TelephonyInfo.h"
@implementation GetAddressBook

+(GetAddressBook *)sharedInstance
{
    static GetAddressBook *getAddressBook;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        getAddressBook = [[GetAddressBook alloc] init];
        
    });
    
    return getAddressBook;
}

-(void)addressBookGetAuthorizationStatus
{
    //檢測狀態 如果狀態是 不同意或者是家長限制 跳出 警告視窗
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied ||
        ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted){
        //1
        NSLog(@"Denied 不同意");
        
        UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot Add Contact" message: @"You must give the app permission to add the contact first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
        
        [cantAddContactAlert show];
        
        //如果同意 就直接提取聯絡人資料
    } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        //2
        NSLog(@"Authorized 同意");
        [self authorizationStatusAuthorized];
        
        //剩下的就是待決定
    } else{ //ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined
        //3
        NSLog(@"Not determined 等待決定中");

        //等待決定 會等客戶選擇完畢才執行block
        ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
            

            dispatch_async(dispatch_get_main_queue(), ^{
                
                //如果不同意 則跳出警告 並且中止這個block
                if (!granted){
                    //4
                    UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot Add Contact" message: @"You must give the app permission to add the contact first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
                    
                    [cantAddContactAlert show];
                    
                    return;
                }
                
                //5 如果客戶同意 則拿取聯絡人資料
                [self authorizationStatusAuthorized];
            });
            
        });
    }
    
}
-(void)authorizationStatusAuthorized
{
    
    self.MA_UserAddressBook = [[NSMutableArray alloc]initWithCapacity:0];
    CFErrorRef error = NULL;
    
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    
    
    NSArray *listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
    
    
    
    NSString *countryNumber = [TelephonyInfo getCountryCodeNumber];
    
    if (countryNumber != nil) {
        //將國碼 加 . 號
        countryNumber = [countryNumber stringByAppendingString:@"."];
    }else
    {
        countryNumber = [TelephonyInfo getLocationCountryCodeNumber];
        countryNumber = [countryNumber stringByAppendingString:@"."];
    }
    
    for (int i=0; i<listContacts.count; i++)
    {
        NSMutableDictionary *MD_UserAddressBookDict = [[NSMutableDictionary alloc]initWithCapacity:0];
        
        //取出單筆聯絡人資料
        ABRecordRef thisPerson = CFBridgingRetain([listContacts objectAtIndex:i]);
        //取得電話
        ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(thisPerson, kABPersonPhoneProperty);
        //取得到電話陣列 因為有可能一個人有多個電話
        NSArray* phoneNumberArray = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(phoneNumberProperty));
        NSLog(@"%@",phoneNumberArray);

        if ([phoneNumberArray count]>0) {
            
            NSLog(@"%@",phoneNumberArray[0]);
            if (![phoneNumberArray[0] isEqualToString:@""]) {
                
                NSString *phone = [NSString stringWithFormat:@"%@",phoneNumberArray[0]];
                NSLog(@"%@",phone);

                //檢查有沒有加
                if ([phone hasPrefix:@"+"]) {
                    
                    //先把 ＋ 去除
                    phone  = [phone stringByReplacingOccurrencesOfString:@"+" withString:@""];
                    NSLog(@"%@",phone);

                    phone  = [phone stringByReplacingOccurrencesOfString:@"-" withString:@" "];
                    NSLog(@"%@",phone);

                    phone  = [phone stringByReplacingOccurrencesOfString:@"#" withString:@""];
                    NSLog(@"%@",phone);


                    //拆解空格
                    NSArray *array = [phone componentsSeparatedByString:@" "];
                    NSLog(@"%@",array);

                    NSString *string = @"";
                    
                    if (array.count>1) {
                        
                        for (int i = 0;  i < array.count; i++) {
                            if (i==0) {
                                
                                string = [string stringByAppendingString:[NSString stringWithFormat:@"%@.",array[i]]];
                                
                            }else
                            {
                                string = [string stringByAppendingString:array[i]];
                            }
                        }

                    }
                    
                    [MD_UserAddressBookDict setObject:string forKey:@"phone"];
                    //[self.MA_UserAddressBook addObject:string];
                    
                }else if ([phone hasPrefix:@"0"])
                {
                    //去除 -
                    phone  = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    
                    //去除空格
                    phone  = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
                    //去除#
                    phone  = [phone stringByReplacingOccurrencesOfString:@"#" withString:@""];
                    
                    //取得文字第一位以後的文字
                    phone = [phone substringFromIndex:1];
                    
                    //將國碼和電話組合
                    phone = [countryNumber stringByAppendingString:phone];
                    
                    //[self.MA_UserAddressBook addObject:phone];
                    [MD_UserAddressBookDict setObject:phone forKey:@"phone"];

                }else if (![phone hasPrefix:@"0"])
                {
                    
                    //去除 -
                    phone  = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    
                    //去除空格
                    phone  = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
                    //去除#
                    phone  = [phone stringByReplacingOccurrencesOfString:@"#" withString:@""];
                    
//                    [self.MA_UserAddressBook addObject:phone];
                    [MD_UserAddressBookDict setObject:phone forKey:@"phone"];

                }
                
                

//                [MD_UserAddressBookDict setObject:phone forKey:@"phone"];
                
                NSString *firstName = CFBridgingRelease(ABRecordCopyValue(thisPerson,kABPersonFirstNameProperty));
                
                NSString *lastName = CFBridgingRelease(ABRecordCopyValue(thisPerson,kABPersonLastNameProperty));
                
                //名稱
                
                if (firstName!=nil&&lastName!=nil) {
                    firstName = [firstName stringByAppendingString:lastName];
                    
                    [MD_UserAddressBookDict setObject:firstName forKey:@"Name"];

                }else if (firstName == nil && lastName !=nil) {
                    
                    [MD_UserAddressBookDict setObject:lastName forKey:@"Name"];
                    
                }else if (lastName == nil && firstName !=nil) {
                    
                    [MD_UserAddressBookDict setObject:firstName forKey:@"Name"];
                }else
                {
                    [MD_UserAddressBookDict setObject:@"無" forKey:@"Name"];

                }
                
                
                //圖片 如果有圖片
                /*
                if(ABPersonHasImageData(thisPerson)){
                    
                    NSData *photoData = CFBridgingRelease(ABPersonCopyImageData(thisPerson));
                    
                    if(photoData){
                        
                        [MD_UserAddressBookDict setObject:photoData forKey:@"image"];
                        
                    }
                }
                */
            }
            
            [self.MA_UserAddressBook addObject:MD_UserAddressBookDict];
        }
        CFRelease(phoneNumberProperty);
        CFRelease(thisPerson);
        
    }
    CFRelease(addressBook);
    //[self searchFreindForServer];
    
    NSLog(@"%@",self.MA_UserAddressBook);

    [self.delegate isAddressBookGetAuthorizationStatus];
}

@end
